<template>
  <div class="stock-record-management">
    <div class="header">
      <h2>库存记录管理</h2>
      <div class="header-buttons">
        <el-button type="primary" @click="showStockInDialog">
          <el-icon><Plus /></el-icon>
          商品入库
        </el-button>
      </div>
    </div>

    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :model="searchForm" label-width="100px" inline>
        <el-form-item label="记录编号">
          <el-input
            v-model="searchForm.recordNo"
            placeholder="请输入记录编号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="商品名称">
          <el-input
            v-model="searchForm.productName"
            placeholder="请输入商品名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="操作类型">
          <el-select v-model="searchForm.recordType" placeholder="请选择操作类型" clearable style="width: 120px">
            <el-option label="入库" value="IN" />
            <el-option label="出库" value="OUT" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <el-table 
      v-loading="loading" 
      :data="tableData" 
      style="width: 100%"
      stripe
    >
      <el-table-column prop="recordNo" label="记录编号" width="180" />
      <el-table-column prop="productName" label="商品名称" min-width="120" />
      <el-table-column prop="productCode" label="商品编号" width="120" />
      <el-table-column prop="recordTypeName" label="操作类型" width="80">
        <template #default="scope">
          <el-tag :type="scope.row.recordType === 'IN' ? 'success' : 'danger'">
            {{ scope.row.recordType === 'IN' ? '入库' : '出库' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="quantity" label="操作数量" width="80" />
      <el-table-column prop="beforeStock" label="操作前库存" width="100" />
      <el-table-column prop="afterStock" label="操作后库存" width="100" />
      <el-table-column prop="operatorName" label="操作员" width="100" />
      <el-table-column prop="createTime" label="操作时间" width="160">
        <template #default="scope">
          {{ formatTime(scope.row.createTime) }}
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-model:current-page="pagination.current"
      v-model:page-size="pagination.size"
      :page-sizes="[10, 20, 50, 100]"
      :total="pagination.total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      style="margin-top: 20px; text-align: right"
    />

    <!-- 入库对话框 -->
    <el-dialog
      title="商品入库"
      v-model="stockInDialogVisible"
      width="500px"
      @closed="resetStockForm"
    >
      <el-form
        ref="stockInFormRef"
        :model="stockForm"
        :rules="stockRules"
        label-width="100px"
      >
        <el-form-item label="选择商品" prop="productId">
          <el-select 
            v-model="stockForm.productId" 
            placeholder="请选择商品" 
            filterable
            style="width: 100%"
            @change="handleProductChange"
          >
            <el-option
              v-for="product in products"
              :key="product.id"
              :label="`${product.productName} (${product.productCode})`"
              :value="product.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="供货库存">
          <el-input :value="`${currentStock} (管理员供货库存)`" disabled />
        </el-form-item>
        <el-form-item label="入库数量" prop="quantity">
          <el-input-number
            v-model="stockForm.quantity"
            :min="1"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="单位成本">
          <el-input :value="`¥${stockForm.unitCost || 0} (供货成本价)`" disabled />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="stockForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="stockInDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleStockIn" :loading="stockSubmitting">确定</el-button>
        </span>
      </template>
    </el-dialog>


  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus, Minus, Search } from '@element-plus/icons-vue'
import {
  stockIn,
  getStockRecordList,
  getAllSupplyProducts
} from '../api/stock'

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const stockInDialogVisible = ref(false)
const stockSubmitting = ref(false)
const stockInFormRef = ref()
const products = ref([]) // 供货商品列表（用于入库）
const currentStock = ref(0)

// 搜索表单
const searchForm = reactive({
  recordNo: '',
  productName: '',
  productCode: '',
  recordType: '',
  operatorName: ''
})

// 分页信息
const pagination = reactive({
  current: 1,
  size: 20,
  total: 0
})

// 库存操作表单
const stockForm = reactive({
  productId: null,
  quantity: 1,
  unitCost: null,
  remark: ''
})

// 表单验证规则
const stockRules = {
  productId: [
    { required: true, message: '请选择商品', trigger: 'change' }
  ],
  quantity: [
    { required: true, message: '请输入数量', trigger: 'blur' },
    { type: 'number', min: 1, message: '数量必须大于0', trigger: 'blur' }
  ]
}

// 页面加载时获取数据
onMounted(() => {
  getTableData()
  getProductList()
})

// 获取表格数据
async function getTableData() {
  loading.value = true
  try {
    const params = {
      page: pagination.current,
      size: pagination.size,
      ...searchForm
    }
    const response = await getStockRecordList(params)
    console.log('库存记录API响应:', response)
    if (response.code === 200) {
      // 修复数据结构 - PageResult使用records字段
      tableData.value = response.data.records || response.data.list || []
      pagination.total = response.data.total
      console.log('设置库存记录数据:', tableData.value)
    } else {
      ElMessage.error(response.message || '获取数据失败')
    }
  } catch (error) {
    console.error('获取库存记录失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 获取商品列表（入库用 - 显示供货商品）
async function getProductList() {
  try {
    console.log('开始获取供货商品列表...')
    const params = { pageNum: 1, pageSize: 1000 }
    console.log('请求参数:', params)
    const response = await getAllSupplyProducts(params)
    console.log('API响应:', response)
    if (response.code === 200) {
      // 修复数据结构 - PageResult使用records字段
      products.value = response.data.records || response.data.list || []
      console.log('设置供货商品列表:', products.value)
    } else {
      console.error('API返回错误:', response.message)
    }
  } catch (error) {
    console.error('获取供货商品列表失败:', error)
  }
}

// 显示入库对话框
function showStockInDialog() {
  resetStockForm()
  stockInDialogVisible.value = true
}

// 商品选择变化（入库用）
function handleProductChange(productId) {
  const product = products.value.find(p => p.id === productId)
  if (product) {
    // 显示供货商品的库存（管理员库存）
    currentStock.value = product.stock || 0
    // 自动设置单位成本为供货商品的成本价
    stockForm.unitCost = product.cost || 0
  } else {
    currentStock.value = 0
    stockForm.unitCost = 0
  }
}



// 处理入库
async function handleStockIn() {
  try {
    await stockInFormRef.value.validate()
    stockSubmitting.value = true
    
    const response = await stockIn({
      productId: stockForm.productId,
      quantity: stockForm.quantity,
      unitCost: stockForm.unitCost,
      remark: stockForm.remark
    })
    
    if (response.code === 200) {
      ElMessage.success('入库成功')
      stockInDialogVisible.value = false
      getTableData()
      // 入库成功后不需要刷新供货商品列表
    } else {
      ElMessage.error(response.message || '入库失败')
    }
  } catch (error) {
    console.error('入库失败:', error)
    ElMessage.error('入库失败')
  } finally {
    stockSubmitting.value = false
  }
}



// 重置库存表单
function resetStockForm() {
  stockForm.productId = null
  stockForm.quantity = 1
  stockForm.unitCost = 0
  stockForm.remark = ''
  currentStock.value = 0

  // 清除验证
  if (stockInFormRef.value) {
    stockInFormRef.value.clearValidate()
  }
}

// 搜索
function handleSearch() {
  pagination.current = 1
  getTableData()
}

// 重置搜索
function resetSearch() {
  Object.assign(searchForm, {
    recordNo: '',
    productName: '',
    productCode: '',
    recordType: '',
    operatorName: ''
  })
  pagination.current = 1
  getTableData()
}

// 分页大小变化
function handleSizeChange(newSize) {
  pagination.size = newSize
  pagination.current = 1
  getTableData()
}

// 当前页变化
function handleCurrentChange(newPage) {
  pagination.current = newPage
  getTableData()
}

// 格式化时间
function formatTime(time) {
  if (!time) return '-'
  return new Date(time).toLocaleString('zh-CN')
}
</script>

<style scoped>
.stock-record-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
}

.header-buttons {
  display: flex;
  gap: 10px;
}

.search-area {
  background: #f5f7fa;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 